package com.gack.business.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gack.business.dao.StoreCameraDao;
import com.gack.business.dao.UserDao;
import com.gack.business.model.Department;
import com.gack.business.model.Invoice;
import com.gack.business.model.Message;
import com.gack.business.model.Order;
import com.gack.business.model.StoreAttention;
import com.gack.business.model.StoreCameras;
import com.gack.business.model.User;
import com.gack.business.model.VideoStores;
import com.gack.business.repository.DepartmentRepository;
import com.gack.business.repository.EnterpriseRepository;
import com.gack.business.repository.InvoiceRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.OrderRepository;
import com.gack.business.repository.StoreAttentionRepository;
import com.gack.business.repository.UserEnterpriseDepartmentPositionRepository;
import com.gack.business.repository.UserRepository;
import com.gack.business.repository.VideoStoresRepository;
import com.gack.business.vo.ListOrders;
import com.gack.helper.common.abstractobj.OrderIdhelper;
import com.gack.helper.common.config.PayConfig;
import com.gack.helper.common.util.HttpGetUtil;
import com.gack.helper.common.util.SendCode;
import com.gack.helper.rabbtit.MessageProvider;
import com.gack.helper.rabbtit.pojo.QueueEnum;
import com.gack.helper.redis.RedisTool;

@Service
public class OrderService {

	double THIRTY_MINUTES = 1800000.00;

	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private VideoStoresRepository storesRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private OrderIdhelper idhelper;
	@Autowired
	private UserEnterpriseDepartmentPositionRepository departmentPositionRepository;
	@Autowired
	private DepartmentRepository departmentRepository;
	@Autowired
	private EnterpriseRepository enterpriseRepository;
	@Autowired
	private MessageProvider messageProvider;
	@Autowired
	private MessageRepository messageRepository;
	@Autowired
	private UserDao userDao;
	@Autowired
	private InvoiceRepository invoiceRepository;
	@Autowired
	private EntityManager entityManager;
	@Autowired
	private StoreCameraServiceInterface cameraService;
	@Autowired
	private StoreCameraDao cameraDao;
	@Autowired
	private RedisTool redisTool;
	@Autowired
	private StoreAttentionServiceInterface storeAttentionService;
	@Autowired
	private JPushServer jPushServer;
	@Autowired
	private StoreAttentionRepository attentionRepository;
	
	/**
	 * 
	 * @Title: reservation 
	 * @Description: 预约·订单
	 * @param userId 用户ID 
	 * @param storeId 门店ID 
	 * @param enterpriseId 公司ID 
	 * @return Map<String,Object> 
	 * @throws
	 */
	public Map<String, Object> reservationLock(String userId, String storeId, String enterpriseId){
		Map<String, Object> result = null;
		try{
			result = reservation(userId, storeId, enterpriseId);
			return result;
		} finally {
			if(result.get("msg").equals("0"))
				redisTool.releaseDistributedLock(storeId, userId);
		}
	}
	
	
	@Transactional
	public Map<String, Object> reservation(String userId, String storeId, String enterpriseId){
		User user = userRepository.findOne(userId);
		VideoStores stores = storesRepository.findStoreById(storeId);
		Map<String, Object> map = new HashMap<>();
		map.put("order", null);
		map.put("state", "FAIL");

		// 用户存在未结算订单
		if (user.getOrderState().intValue() == 0) {
			// 门店未被使用且可被使用
			if (stores.getIsUse().intValue() == 0 && stores.getStatus().intValue() == 1) {
				// if(!user.is_check()) {
				// map.put("msg", "1");// 用户未认证
				// return map;
				// }
				// else if(user.getIsPledge() == 0) {
				// map.put("msg", "2");// 用户未缴纳押金
				// return map;
				// } else if(user.getIsPledge() == 2) {
				// map.put("msg", "3");// 用户押金退款中
				// return map;
				// }
				boolean result = false;
				try{
					
					result = redisTool.tryGetDistributedLock(storeId, userId, 5000);
					System.out.println(result);
					if(!result){
						map.put("msg", "4");// 门店不可预约
						return map;
					} else {
						map.put("msg", "0");// 抢占锁成功
					}
					// 门店状态保存
					stores.setStatus(2);
					storesRepository.save(stores);
	
					// 预约信息
					Order order = new Order();
					order.setUserId(userId);
					order.setStoreId(storeId);
					order.setOrderId(idhelper.getOrderId());
					order.setEnterpriseId(enterpriseId);
					order.setStatus("1");
					orderRepository.save(order);
					// 用户状态保存
					user.setOrderState(2);
					userRepository.save(user);
	
					map.put("state", "SUCCESS");
					map.put("order", order);
	
					// 预约成功 向门店管理者及用户发送短信
					// SendCode.sendMessage(user.getUsername(),
					// "您已成功预约，在订单开始使用前预约状态将会保留30分钟，预约保留时间到达后会自动取消预约订单，请准时到达");
					// sendCode.sendMessage(store.getStorePhone(),
					// "有用户成功预约门店，请做好准备，确保门店设备正常使用");
					SendCode.sendMessage(stores.getStorePhone(),
							"手机尾号为" + user.getUsername().substring(7) + "客户，已经预约您的门店进行办公，预计三十分钟内到达使用。");
					messageProvider.sendMessage(order.getId(), QueueEnum.MESSAGE_TTL_QUEUE.getExchange(),
							QueueEnum.MESSAGE_TTL_QUEUE.getRouteKey(), 1800000);
					
					// 门店状态修改 通知设备刷新门店
					jPushServer.sendPush("", "22", "", null);
				}catch (Exception e) {
					e.printStackTrace();
				}
//				finally {
//					if(result)
//						redisTool.releaseDistributedLock(storeId, userId);
//				}
				return map;
			}
			map.put("msg", "4");// 门店不可预约
			return map;
		}
		map.put("msg", "5");// 存在未结算订单
		return map;
	}

	/**
	 * 
	 * @Title: begin @Description: 开始使用 @param id 订单ID @param beginTime
	 * 开始时间 @return Map<String,Object> @throws
	 */
	@Transactional
	public Map<String, Object> begin(String id) {
		Map<String, Object> map = new HashMap<>();

		Order order = orderRepository.findOne(id);
		map.put("state", "FAIL");
		map.put("order", null);
		if (order != null && order.getStatus().equals("1")) {
			order.setBeginTime(new Date());
			order.setStatus("4");
			orderRepository.save(order);

			User user = userRepository.findOne(order.getUserId());
			// VideoStores stores =
			// storesRepository.findOne(order.getStoreId());
			user.setCreate_office_num((user.getCreate_meeting_num() == null ? 0 : user.getCreate_meeting_num()) + 1);
			// 用户状态保存
			user.setOrderState(2);
			userRepository.save(user);
			// // 门店状态保存
			// stores.setStatus(2);
			// storesRepository.save(stores);
			// 查询订单门店 及 门店设备列表
			order.setStore(storesRepository.findOne(order.getStoreId()));
			order.getStore().setCameras(cameraDao.getStoreCameras(order.getStoreId()));
			// 门店状态修改 通知设备刷新门店
			jPushServer.sendPush("", "22", "", null);

			map.put("state", "SUCCESS");
			map.put("order", order);
			return map;
		}
		map.put("msg", "订单信息异常");
		return map;

	}

	/**
	 * 
	 * @Title: cancelReservation @Description: 取消预约订单 @param id @return
	 * Map<String,Object> @throws
	 */
	@Transactional
	public Map<String, Object> cancelReservation(String id, String cancelReason, String text) throws Exception {
		Map<String, Object> map = new HashMap<>();
		Order order = orderRepository.findOne(id);
		map.put("state", "FAIL");
		map.put("order", null);
		if (order != null) {
			if (!order.getStatus().equals("1")) {
				map.put("msg", "订单已取消预约或不可取消预约");
				return map;
			}

			order.setStatus(text.equals("1") ? "2" : "3");
			order.setCancelReason(cancelReason);
			orderRepository.save(order);

			User user = userRepository.findOne(order.getUserId());
			VideoStores stores = storesRepository.findOne(order.getStoreId());

			// 用户状态保存
			user.setOrderState(0);
			userRepository.save(user);
			// 门店状态保存
			stores.setStatus(1);
			storesRepository.save(stores);

			Message message = new Message();

			message.setMessage("您预约的会议室（" + stores.getStoreName() + "）已取消");
			message.setTitle("预约消息提醒");
			message.setMesType(4);
			message.setSendWay(2);
			message.setUserid(order.getUserId());
			message.setCreatetime(new Date());
			messageRepository.save(message);

			// 短信通知店铺管理者及用户
			// SendCode.sendMessage(user.getUsername(), "您已成功取消店铺预约");
			SendCode.sendMessage(stores.getStorePhone(),
					"手机尾号为" + user.getUsername().substring(7) + "客户，已经取消预约您的门店进行办公。");

			// 门店状态修改 通知设备刷新门店
			jPushServer.sendPush("", "22", "", null);
			
			map.put("state", "SUCCESS");
			map.put("order", order);
			return map;
		}
		map.put("msg", "未找到订单");
		return map;

	}

	public int getMoney(String id) {
		Map<String, Object> map = new HashMap<>();
		Order order = orderRepository.findOne(id);
		if (order.getStatus().equals("4")) {
			VideoStores stores = storesRepository.findOne(order.getStoreId());
			Date beginDate = order.getBeginTime();
			Date date = new Date();
			int result = (int) Math.ceil((date.getTime() - beginDate.getTime()) / THIRTY_MINUTES);
			result = (result <= 2 ? 2 : result);
			int amount = (result * stores.getStorePrice() * 50);
			return amount;
		}
		return 0;
	}

//	/**
//	 * 
//	 * @Title: end @Description: 结束订单 @param id 订单ID @return
//	 * Map<String,Object> @throws
//	 */
//	@Transactional
//	public Map<String, Object> end(String id) throws Exception {
//		Map<String, Object> map = new HashMap<>();
//		Order order = orderRepository.findOne(id);
//		map.put("state", "FAIL");
//		map.put("order", null);
//		// 订单使用中结束进入预支付
//		if (order == null) {
//			map.put("msg", "未找到订单");
//			return map;
//		}
//
//		if (order.getStatus().equals("4")) {
//			User user = userRepository.findOne(order.getUserId());
//			VideoStores stores = storesRepository.findOne(order.getStoreId());
//			// 解除门店状态
//			stores.setStatus(1);
//			storesRepository.save(stores);
//			// 订单结算
//			Date date = new Date();
//			order.setStatus("5");
//			order.setEndTime(date);
//			Date beginDate = order.getBeginTime();
//			int result = (int) Math.ceil((date.getTime() - beginDate.getTime()) / THIRTY_MINUTES);
//			result = (result <= 2 ? 2 : result);
//			int amount = (result * stores.getStorePrice() * 50);
//			amount = 1;//测试
//			order.setAmount(amount);// 单位fen
//			order.setCardAmount(0);
//
//			// 门店订单保存
//			SendCode.sendMessage(stores.getStorePhone(),
//					"手机尾号为" + user.getUsername().substring(7) + "客户, 已使用结束，请注意收费，并及时对会议室进行维护。谢谢！");
//
//			// 用户状态保存
//			user.setOrderState(3);
//			userRepository.save(user);
//		}
//
//		// --------------- 二期修改
//
//		order.setPayAmount(1);
//		order.setStatus("5");// 上商务卡后修改
//		order.setBusinessCardAmount(0);
//		orderRepository.save(order);
//
//		// Session session = (Session)entityManager.getDelegate();
//		// session.evict(order);
//		// ---------------
//
//		// 调用押金支付接口
//		/*
//		 * String baseUrl = PayConfig.PAY_URL; StringBuffer url = new
//		 * StringBuffer();
//		 * url.append(baseUrl).append("?uid=").append(order.getUserId()).append(
//		 * "&systemCode=").append("11")
//		 * .append("&channel=").append("free_com").append("&amount=").append(
//		 * order.getPayAmount()).append("&card_type=")
//		 * .append("7").append("&originalId=").append("DDCCBBAA"); String result
//		 * = HttpGetUtil.httpGet(url.toString()); System.out.println(result);
//		 * JSONObject parseObject = JSON.parseObject(result); Map<String,
//		 * Object> payMap = JSON.toJavaObject(parseObject, Map.class);
//		 * if(payMap.get("status").toString().equals("SUCCESS"))
//		 * order.setPingId(payMap.get("id").toString());
//		 */
//
//		// orderRepository.save(order);
//
//		map.put("order", order);
//		map.put("state", "SUCCESS");
//
//		// 查看用户所在所有部门
//		// List<String> departmentIds =
//		// departmentPositionRepository.findDepartmentIdsByUserId(order.getUserId());
//		// if(departmentIds != null){
//		// while(departmentIds != null && departmentIds.contains(null))
//		// departmentIds.remove(null);
//		// }
//		//
//		// if(departmentIds.size() > 0) {
//		//
//		// // 部门详情
//		// List<Department> lists = departmentRepository.findAll(departmentIds);
//		// CopyOnWriteArrayList<Department> departments = new
//		// CopyOnWriteArrayList<>(lists);
//		// // 循环遍历剔除不是一级部门的部门找到不是一部门对应的部门
//		// for(Department department : departments){
//		// while(department != null){
//		// if(!department.getParentId().equals("0")){
//		// if(departments.contains(department))
//		// departments.remove(department);
//		// department = departmentRepository.findOne(department.getParentId());
//		// }else {
//		// break;
//		// }
//		// }
//		// }
//		//
//		// if(departments.size() > 0) {
//		//
//		// map.put("state", "SUCCESS");
//		// Map<String, Object> amounts = new HashMap<>();
//		// for (Department department : departments) {
//		// Enterprise enterprise =
//		// enterpriseRepository.findOne(department.getEnterpriseId());
//		// amounts.put(department.getId(), new
//		// KeyValue(enterprise.getId(),enterprise.getName(),String.valueOf(department.getSurplus_amount())));
//		// }
//		//
//		// map.put("amounts", amounts);
//		// map.put("order", order);
//		// map.put("state", "SUCCESS");
//		// return map;
//		// }
//		//
//		// }else {
//		// order.setStatus("6");
//		// order.setCardAmount(0);
//		// orderRepository.save(order);
//		// map.put("order", order);
//		// map.put("state", "SUCCESS");
//		// }
//		return map;
//	}

	/**
	 * 
	 * @Title: prePay @Description: 发起预支付订单 *********暂不使用 @param id 订单ID @param
	 * departmentId 部门ID @param surplusAmount 使用金额 @return
	 * Map<String,Object> @throws
	 */
	@Transactional
	public Map<String, Object> prePay(String id, String departmentId, Integer surplusAmount) {
		Map<String, Object> map = new HashMap<>();
		Order order = orderRepository.findOne(id);
		Department department = departmentRepository.findOne(departmentId);
		map.put("state", "FAIL");
		if (order != null && order.getStatus().equals("5") && department != null
				&& department.getSurplus_amount() > surplusAmount) {
			User user = userRepository.findOne(order.getUserId());
			department.setSurplus_amount(department.getSurplus_amount() - surplusAmount);
			department.setUsed_amount(department.getUsed_amount() + surplusAmount);

			departmentRepository.save(department);

			order.setEnterpriseId(department.getEnterpriseId());
			order.setDepartmentId(departmentId);
			order.setStatus("6");
			order.setBusinessCardAmount(surplusAmount);
			order.setPayAmount(order.getAmount() - surplusAmount);
			// 若为商务卡全额支付
			if (surplusAmount == order.getAmount()) {
				// 用户状态保存
				user.setOrderState(0);
				userRepository.save(user);

				order.setStatus("9");
				order.setPayTime(new Date());
				// 调用押金支付接口
				String baseUrl = PayConfig.PAY_URL;
				StringBuffer url = new StringBuffer();
				url.append(baseUrl).append("?uid=").append(order.getUserId()).append("&systemCode=").append("11")
						.append("&channel=").append("free_com").append("&amount=").append(order.getPayAmount() * 100)
						.append("&card_type=").append("7").append("&originalId=").append("DDCCBBAA");
				String result = HttpGetUtil.httpGet(url.toString());
				System.out.println(result);
				JSONObject parseObject = JSON.parseObject(result);
				Map<String, Object> payMap = JSON.toJavaObject(parseObject, Map.class);
				if (payMap.get("status").toString().equals("SUCCESS"))
					order.setPingId(payMap.get("id").toString());
			}

			orderRepository.save(order);

			map.put("state", "SUCCESS");
			map.put("order", order);
			return map;
		}
		map.put("msg", "订单信息异常");
		return map;
	}

//	/**
//	 * 
//	 * @Title: prePay @Description: 结算预支付订单 @param id 订单ID @return
//	 * Map<String,Object> @throws
//	 */
//	@Transactional
//	public Map<String, Object> pay(String id, String channel,HttpServletRequest request) {
//		Map<String, Object> map = new HashMap<>();
//		Order order = orderRepository.findOne(id);
//		map.put("state", "FAIL");
//		map.put("order", null);
//		if (order != null
//				&& (order.getStatus().equals("5") || order.getStatus().equals("6") || order.getStatus().equals("7"))) {
//			map.put("state", "SUCCESS");
//			order.setStatus("7");//10 全额优惠卷支付
//			// 调用订单支付接口
//			VideoStores stores = storesRepository.findOne(order.getStoreId());
//			String baseUrl = PayConfig.PAY_URL;
//			StringBuffer url = new StringBuffer();
//			try {
////				url.append(baseUrl).append("?uid=").append(order.getUserId()).append("&systemCode=").append("11")
////						.append("&channel=").append("free_com").append("&amount=").append(order.getAmount())
////						.append("&card_type=").append("1").append("&originalId=").append("DDCCBBAA")
////						.append("&card_amount=").append(order.getCardAmount()).append("&business_card_type=")
////						.append("0").append("&store_infor").append(URLEncoder.encode(stores.getStoreName(), "UTF-8"))
////						.append("&platOrderId=").append(order.getId()).append("&create_ip=").append(getIp(request));
//				url.append(baseUrl).append("?uid=").append(order.getUserId()).append("&systemCode=").append("11")
//				.append("&channel=").append(channel).append("&amount=").append(order.getAmount())
//				.append("&card_type=").append("1").append("&originalId=").append("AABBCCDD")
//				.append("&card_amount=").append(order.getCardAmount()).append("&business_card_type=")
//				.append("9").append("&store_infor=").append(URLEncoder.encode(stores.getStoreName(), "UTF-8"))
//				.append("&platOrderId=").append(order.getId()).append("&create_ip=").append(getIp(request))
//				.append("&companyName=1&companyTitle=1");
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			}
//			System.out.println(url);
//			String result = HttpGetUtil.httpGet(url.toString());
//			System.out.println(result);
//			JSONObject parseObject = JSON.parseObject(result);
//			Map<String, Object> payMap = JSON.toJavaObject(parseObject, Map.class);
//			if (payMap.get("status").toString().equals("SUCCESS")){
//				order.setPingId(payMap.get("id").toString());
//				order.setType(channel);
//			}
//				
//
//			if("alipay".equals(channel)){
//				map.put("alipay", payMap.get("body"));
//				map.put("wx", null);
//			}	
//			if("wx".equals(channel)){
//				map.put("wx", payMap.get("body"));
//				map.put("alipay", null);
//			}
//				
//			orderRepository.save(order);
//			User user = userRepository.findOne(order.getUserId());
//			user.setOrderState(0);
//			userRepository.save(user);
//			// VideoStores stores =
//			// storesRepository.findOne(order.getStoreId());
//			// // 调用支付接口
//			// String baseUrl = PayConfig.PAY_URL;
//			// StringBuffer url = new StringBuffer();
//			// url.append(baseUrl).append("?uid=").append(order.getUserId()).append("&systemCode=").append("11")
//			// .append("&channel=").append(channel).append("&amount=").append(order.getPayAmount())
//			// .append("&originalId=").append("AABBCCDD").append("&platOrderId=").append(order.getId())
//			// .append("&store_infor=");
//			// if(order.getPayAmount().intValue() == 0) {
//			// url.append("&business_card_type=").append("9");
//			// } else {
//			// url.append("&business_card_type=").append("8");
//			// }
//			// try {
//			// url.append(URLEncoder.encode(stores.getStoreName(),"UTF-8"));
//			// } catch (UnsupportedEncodingException e) {
//			// e.printStackTrace();
//			// }
//			// System.out.println(url);
//			// String result = HttpGetUtil.httpGet(url.toString());
//			// System.out.println(result);
//			// JSONObject parseObject = JSON.parseObject(result);
//			// Map<String, Object> payMap = JSON.toJavaObject(parseObject,
//			// Map.class);
//			// // 保存订单信息
//			// if(payMap.get("status").toString().equals("SUCCESS"))
//			// order.setPingId(payMap.get("id").toString());
//			// order.setType(channel);
//			// order.setStatus("7");
//			// orderRepository.save(order);
//			map.put("order", order);
//			// map.put("pay", payMap);
//			return map;
//		}
//		map.put("msg", "订单信息异常");
//		return map;
//	}

	/**
	 * 
	 * @Title: end @Description: 结束订单 @param id 订单ID @return
	 * Map<String,Object> @throws
	 */
	@Transactional
	public Map<String, Object> end(String id) throws Exception {
		Map<String, Object> map = new HashMap<>();
		Order order = orderRepository.findOne(id);
		map.put("state", "FAIL");
		map.put("order", null);
		// 订单使用中结束进入预支付
		if (order == null) {
			map.put("msg", "未找到订单");
			return map;
		}

		if (order.getStatus().equals("4")) {
			User user = userRepository.findOne(order.getUserId());
			VideoStores stores = storesRepository.findOne(order.getStoreId());
			// 解除门店状态
			stores.setStatus(1);
			storesRepository.save(stores);
			// 订单结算
			Date date = new Date();
			order.setStatus("5");
			order.setEndTime(date);
			Date beginDate = order.getBeginTime();
			int result = (int) Math.ceil((date.getTime() - beginDate.getTime()) / THIRTY_MINUTES);
			result = (result <= 2 ? 2 : result);
			int amount = (result * stores.getStorePrice() * 50);
			order.setAmount(amount);// 单位fen
			order.setCardAmount(amount);

			// 门店订单保存
			SendCode.sendMessage(stores.getStorePhone(),
					"手机尾号为" + user.getUsername().substring(7) + "客户, 已使用结束，请注意收费，并及时对会议室进行维护。谢谢！");

			// 门店状态修改 通知设备刷新门店
			jPushServer.sendPush("", "22", "", null);
			
			// 用户状态保存
			user.setOrderState(3);
			userRepository.save(user);
		}

		// --------------- 二期修改

		order.setPayAmount(0);
		order.setStatus("5");// 上商务卡后修改
		order.setBusinessCardAmount(0);
		orderRepository.save(order);

		// Session session = (Session)entityManager.getDelegate();
		// session.evict(order);
		// ---------------

		// 调用押金支付接口
		/*
		 * String baseUrl = PayConfig.PAY_URL; StringBuffer url = new
		 * StringBuffer();
		 * url.append(baseUrl).append("?uid=").append(order.getUserId()).append(
		 * "&systemCode=").append("11")
		 * .append("&channel=").append("free_com").append("&amount=").append(
		 * order.getPayAmount()).append("&card_type=")
		 * .append("7").append("&originalId=").append("DDCCBBAA"); String result
		 * = HttpGetUtil.httpGet(url.toString()); System.out.println(result);
		 * JSONObject parseObject = JSON.parseObject(result); Map<String,
		 * Object> payMap = JSON.toJavaObject(parseObject, Map.class);
		 * if(payMap.get("status").toString().equals("SUCCESS"))
		 * order.setPingId(payMap.get("id").toString());
		 */

		// orderRepository.save(order);

		map.put("order", order);
		map.put("state", "SUCCESS");

		// 查看用户所在所有部门
		// List<String> departmentIds =
		// departmentPositionRepository.findDepartmentIdsByUserId(order.getUserId());
		// if(departmentIds != null){
		// while(departmentIds != null && departmentIds.contains(null))
		// departmentIds.remove(null);
		// }
		//
		// if(departmentIds.size() > 0) {
		//
		// // 部门详情
		// List<Department> lists = departmentRepository.findAll(departmentIds);
		// CopyOnWriteArrayList<Department> departments = new
		// CopyOnWriteArrayList<>(lists);
		// // 循环遍历剔除不是一级部门的部门找到不是一部门对应的部门
		// for(Department department : departments){
		// while(department != null){
		// if(!department.getParentId().equals("0")){
		// if(departments.contains(department))
		// departments.remove(department);
		// department = departmentRepository.findOne(department.getParentId());
		// }else {
		// break;
		// }
		// }
		// }
		//
		// if(departments.size() > 0) {
		//
		// map.put("state", "SUCCESS");
		// Map<String, Object> amounts = new HashMap<>();
		// for (Department department : departments) {
		// Enterprise enterprise =
		// enterpriseRepository.findOne(department.getEnterpriseId());
		// amounts.put(department.getId(), new
		// KeyValue(enterprise.getId(),enterprise.getName(),String.valueOf(department.getSurplus_amount())));
		// }
		//
		// map.put("amounts", amounts);
		// map.put("order", order);
		// map.put("state", "SUCCESS");
		// return map;
		// }
		//
		// }else {
		// order.setStatus("6");
		// order.setCardAmount(0);
		// orderRepository.save(order);
		// map.put("order", order);
		// map.put("state", "SUCCESS");
		// }
		return map;
	}
	/**
	 * 
	 * @Title: prePay @Description: 结算预支付订单 @param id 订单ID @return
	 * Map<String,Object> @throws
	 */
	@Transactional
	public Map<String, Object> pay(String id, String channel,HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		Order order = orderRepository.findOne(id);
		map.put("state", "FAIL");
		map.put("order", null);
		if (order != null
				&& (order.getStatus().equals("5") || order.getStatus().equals("6") || order.getStatus().equals("7"))) {
			map.put("state", "SUCCESS");
			order.setStatus("10");
			// 调用订单支付接口
			VideoStores stores = storesRepository.findOne(order.getStoreId());
			/*
			 * 暂时关闭订单支付调用
			String baseUrl = PayConfig.PAY_URL;
			StringBuffer url = new StringBuffer();
			try {
				url.append(baseUrl).append("?uid=").append(order.getUserId()).append("&systemCode=").append("11")
						.append("&channel=").append("free_com").append("&amount=").append(order.getAmount())
						.append("&card_type=").append("1").append("&originalId=").append("DDCCBBAA")
						.append("&card_amount=").append(order.getCardAmount()).append("&business_card_type=")
						.append("0").append("&store_infor").append(URLEncoder.encode(stores.getStoreName(), "UTF-8"))
						.append("&platOrderId=").append(order.getId()).append("&create_ip=").append(getIp(request));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			System.out.println(url);
			String result = HttpGetUtil.httpGet(url.toString());
			System.out.println(result);
			JSONObject parseObject = JSON.parseObject(result);
			Map<String, Object> payMap = JSON.toJavaObject(parseObject, Map.class);
			if (payMap.get("status").toString().equals("SUCCESS"))
				order.setPingId(payMap.get("id").toString());*/
			orderRepository.save(order);
			User user = userRepository.findOne(order.getUserId());
			user.setOrderState(0);
			userRepository.save(user);
			// VideoStores stores =
			// storesRepository.findOne(order.getStoreId());
			// // 调用支付接口
			// String baseUrl = PayConfig.PAY_URL;
			// StringBuffer url = new StringBuffer();
			// url.append(baseUrl).append("?uid=").append(order.getUserId()).append("&systemCode=").append("11")
			// .append("&channel=").append(channel).append("&amount=").append(order.getPayAmount())
			// .append("&originalId=").append("AABBCCDD").append("&platOrderId=").append(order.getId())
			// .append("&store_infor=");
			// if(order.getPayAmount().intValue() == 0) {
			// url.append("&business_card_type=").append("9");
			// } else {
			// url.append("&business_card_type=").append("8");
			// }
			// try {
			// url.append(URLEncoder.encode(stores.getStoreName(),"UTF-8"));
			// } catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			// }
			// System.out.println(url);
			// String result = HttpGetUtil.httpGet(url.toString());
			// System.out.println(result);
			// JSONObject parseObject = JSON.parseObject(result);
			// Map<String, Object> payMap = JSON.toJavaObject(parseObject,
			// Map.class);
			// // 保存订单信息
			// if(payMap.get("status").toString().equals("SUCCESS"))
			// order.setPingId(payMap.get("id").toString());
			// order.setType(channel);
			// order.setStatus("7");
			// orderRepository.save(order);
			map.put("order", order);
			// map.put("pay", payMap);
			return map;
		}
		map.put("msg", "订单信息异常");
		return map;
	}
	
	/**
	 * 
	 * @Title: backPay @Description: 支付系统回调 @param pingId 支付ID @return
	 * Map<String,Object> @throws
	 */
	@Transactional
	public String backPay(String pingId,HttpServletRequest request) {
		
//		if(!"123.56.49.95".equals(getIp(request)))
//			return "ERROR";
		
		Map<String, Object> map = new HashMap<>();
		Order order = orderRepository.findByPingId(pingId);
		map.put("state", "FAIL");
		if (order != null && order.getStatus().equals("7")) {
			// 用户消费次数累计
			User user = userRepository.findOne(order.getUserId());
			user.setExpense_amount(user.getExpense_amount() + order.getPayAmount());
			user.setExpense_num(user.getExpense_amount() + 1);
			user.setOrderState(0);
			userRepository.save(user);
			// 开发票 别忘了
			VideoStores stores = storesRepository.findOne(order.getStoreId());
			Invoice invoice = new Invoice();
			invoice.setOid(order.getPingId());
			invoice.setUid(order.getUserId());
			invoice.setAmout(order.getPayAmount());
			invoice.setOrderTime(order.getCreatedTime());
			invoice.setName(stores.getStoreName());
			invoice.setInfo(String.valueOf((order.getEndTime().getTime() - order.getBeginTime().getTime())));// 使用时间
																												// 毫秒

			invoice.setKind("2");
			invoiceRepository.save(invoice);
			order.setStatus("8");
			order.setPayTime(new Date());
			orderRepository.save(order);
			return "SUCCESS";
		}
		map.put("msg", "订单信息异常");
		return "ERROR";

	}

	public ListOrders findOrderVoByUserId(String userId, int page, int pageSize) {
		// PageRequest pageRequest = new PageRequest(page,pageSize);
		// // 先根据状态倒序排列，再根据创建时间倒序排序，再分页。
		// List<org.springframework.data.domain.Sort.Order> orders=new
		// ArrayList<org.springframework.data.domain.Sort.Order>();
		// // 按照创建时间倒叙
		// orders.add(new
		// org.springframework.data.domain.Sort.Order(Direction.DESC,
		// "createdTime"));
		//
		// Page<OrderVo> pages =
		// orderRepository.findOrdersByUserId(userId,pageRequest);
		// List<OrderVo> vos = pages.getContent();
		// long allPage = pages.getTotalPages();
		// long total = pages.getTotalElements();

		// List<OrderVo> list = orderRepository.findOrdersByUserId(userId);

		return userDao.findOrdersByUserId(userId, page, pageSize);
	}

	public Map<String, Object> userOrder(String userId) {
		User user = userRepository.findOne(userId);
		Map<String, Object> map = new HashMap<>();
		if (!user.getOrderState().equals("0")) {
			Order order = orderRepository.findByUserIdOrderByCreatedTimeDesc(userId);
			map.put("state", "FAIL");
			map.put("order", order);
			return map;
		}
		map.put("state", "FAIL");
		return map;
	}

	public Map<String, Object> orderDetails(String id) {
		Map<String, Object> map = new HashMap<>();
		Order order = orderRepository.findOne(id);
		VideoStores store = storesRepository.findOne(order.getStoreId());
		StoreCameras cameras = cameraDao.getStoreCameras(order.getStoreId());
		List<StoreAttention> attentions = attentionRepository.findAll();
		String attention = (attentions != null && attentions.size() > 0) ? attentions.get(0).getAttention() : null;
		store.setAttention(attention);
		map.put("order", order);
		map.put("store", store);
		map.put("cameras", cameras);
//		map.put("attention", attention);
		return map;
	}

	public Map<String, Object> getUserUsingOrReservedOrder(String userid) {
		Map<String, Object> map = new HashMap<>();
		if (userid == null || userid.equals("")) {
			map.put("key", "error");
			map.put("msg", "id不可为空");
			return map;
		}
		User user = userRepository.findOne(userid);
		if (user == null) {
			map.put("key", "error");
			map.put("msg", "用户不存在");
			return map;
		}
		Order orders = orderRepository.findByUserIdOrderByCreatedTimeDesc(userid);
		if (orders == null) {
			map.put("key", "error");
			map.put("msg", "用户不存在预约或使用中订单");
			return map;
		}
		if (orders != null) {
			orders.setStore(storesRepository.findOne(orders.getStoreId()));
			if (orders.getStatus().equals("4")) {
				orders.getStore().setCameras(cameraDao.getStoreCameras(orders.getStoreId()));
			}
		}
		String msg = (orders.getStatus().equals("1")) ? "预约中" : orders.getStatus().equals("4") ? "使用中" : "待支付";
		map.put("key", "success");
		map.put("msg", "存在"+msg+"订单");
		map.put("order", orders);
		map.put("status", orders.getStatus());
		return map;
	}

	public Map<String, Object> findOrderformInfoByUserId(String id) {
		Map<String, Object> map = new HashMap<>();
		User user = userRepository.findOne(id);
		if (user != null) {
			List<Order> orders = orderRepository.getUserUsingOrReservedOrder(user.getId());
			if (orders != null && orders.size() > 0) {
				Order order = orders.get(0);
				if (order != null) {
					order.setStore(storesRepository.findOne(order.getStoreId()));
					if (order.getStatus().equals("4")) {
						order.getStore().setCameras(cameraDao.getStoreCameras(order.getStoreId()));
					}
					// 查询出可用订单详情，返回
					Map<String, Object> orderMap = new HashMap<>();
					String msg = (order.getStatus().equals("1")) ? "预约中" : order.getStatus().equals("4") ? "使用中" : "待支付";
					map.put("key", "success");
					map.put("value", order);
					map.put("msg", "存在"+msg+"订单");
				}
			} else {
				map.put("key", "error");
				map.put("msg", "用户不存在预约或使用中订单，订单详情查询失败");
			}
		} else {
			map.put("key", "error");
			map.put("msg", "该用户不存在，订单详情查询失败");
		}
		return map;
	}
	@Transactional
	public String closeeOrderByStoreName(String storeName){
		
		VideoStores store = storesRepository.findByStoreName(storeName);
		if(store == null)
			return "storeName not found";
		Order order = orderRepository.findByStoreId(store.getId());
		if(order == null)
			return "store order not found";
		
		User user = userRepository.findOne(order.getUserId());
		user.setOrderState(0);
		userRepository.save(user);
		
		store.setStatus(1);
		storesRepository.save(store);
		
		order.setAmount(0);
		order.setPayAmount(0);
		order.setCardAmount(0);
		order.setBusinessCardAmount(0);
		order.setStatus("10");
		orderRepository.save(order);
		
		// 门店状态修改 通知设备刷新门店
		jPushServer.sendPush("", "22", "", null);
	
		return "SUCCESS";

		
	}

	// 获取用户真实IP
	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		System.out.println("x-forwarded-for ip: " + ip);
		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			if (ip.indexOf(",") != -1) {
				ip = ip.split(",")[0];
			}
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
			System.out.println("Proxy-Client-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
			System.out.println("WL-Proxy-Client-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
			System.out.println("HTTP_CLIENT_IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
			System.out.println("X-Real-IP ip: " + ip);
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			System.out.println("getRemoteAddr ip: " + ip);
		}
		return ip;
	}
}
